home *** CD-ROM | disk | FTP | other *** search
/ Die Speccy' 97 / Die Speccy' 97.iso / amiga_system / the_aminet / dev / lang / python_src.lha / amigapython / python / pythonrun.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-10-22  |  14.6 KB  |  762 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Python interpreter top-level routines, including init/exit */
  26.  
  27. #include "allobjects.h"
  28.  
  29. #include "grammar.h"
  30. #include "node.h"
  31. #include "parsetok.h"
  32. #include "graminit.h"
  33. #undef argument /* Avoid conflict on Mac */
  34. #include "errcode.h"
  35. #include "sysmodule.h"
  36. #include "bltinmodule.h"
  37. #include "compile.h"
  38. #include "eval.h"
  39. #include "ceval.h"
  40. #include "pythonrun.h"
  41. #include "import.h"
  42. #include "marshal.h"
  43.  
  44. #ifdef HAVE_SIGNAL_H
  45. #include <signal.h>
  46. #endif
  47.  
  48. #ifdef THINK_C
  49. #include <console.h>
  50. #endif
  51.  
  52. #ifdef __MWERKS__
  53. #include <SIOUX.h>
  54. #endif
  55.  
  56. #ifdef NT
  57. #undef BYTE
  58. #include "windows.h"
  59. #endif
  60.  
  61. extern char *getpythonpath();
  62.  
  63. extern grammar gram; /* From graminit.c */
  64.  
  65. /* Forward */
  66. static void initmain PROTO((void));
  67. static object *run_err_node PROTO((node *n, char *filename,
  68.                    object *globals, object *locals));
  69. static object *run_node PROTO((node *n, char *filename,
  70.                    object *globals, object *locals));
  71. static object *run_pyc_file PROTO((FILE *fp, char *filename,
  72.                    object *globals, object *locals));
  73. static void err_input PROTO((perrdetail *));
  74. static void initsigs PROTO((void));
  75.  
  76. int debugging; /* Needed by parser.c */
  77. int verbose; /* Needed by import.c */
  78. int suppress_print; /* Needed by ceval.c */
  79.  
  80. /* Initialize all */
  81.  
  82. void
  83. initall()
  84. {
  85.     static int inited;
  86.     
  87.     if (inited)
  88.         return;
  89.     inited = 1;
  90.     
  91.     initimport();
  92.     
  93.     /* Modules '__builtin__' and 'sys' are initialized here,
  94.        they are needed by random bits of the interpreter.
  95.        All other modules are optional and are initialized
  96.        when they are first imported. */
  97.     
  98.     initbuiltin(); /* Also initializes builtin exceptions */
  99.     initsys();
  100.  
  101.     setpythonpath(getpythonpath());
  102.  
  103.     initsigs(); /* Signal handling stuff, including initintr() */
  104.  
  105.     initmain();
  106. }
  107.  
  108. /* Create __main__ module */
  109.  
  110. static void
  111. initmain()
  112. {
  113.     object *m, *d;
  114.     m = add_module("__main__");
  115.     if (m == NULL)
  116.         fatal("can't create __main__ module");
  117.     d = getmoduledict(m);
  118.     if (dictlookup(d, "__builtins__") == NULL) {
  119.         if (dictinsert(d, "__builtins__", getbuiltins()))
  120.             fatal("can't add __builtins__ to __main__");
  121.     }
  122. }
  123.  
  124. /* Parse input from a file and execute it */
  125.  
  126. int
  127. run(fp, filename)
  128.     FILE *fp;
  129.     char *filename;
  130. {
  131.     if (filename == NULL)
  132.         filename = "???";
  133.     if (isatty((int)fileno(fp)))
  134.         return run_tty_loop(fp, filename);
  135.     else
  136.         return run_script(fp, filename);
  137. }
  138.  
  139. int
  140. run_tty_loop(fp, filename)
  141.     FILE *fp;
  142.     char *filename;
  143. {
  144.     object *v;
  145.     int ret;
  146.     v = sysget("ps1");
  147.     if (v == NULL) {
  148.         sysset("ps1", v = newstringobject(">>> "));
  149.         XDECREF(v);
  150.     }
  151.     v = sysget("ps2");
  152.     if (v == NULL) {
  153.         sysset("ps2", v = newstringobject("... "));
  154.         XDECREF(v);
  155.     }
  156.     for (;;) {
  157.         ret = run_tty_1(fp, filename);
  158. #ifdef REF_DEBUG
  159.         fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  160. #endif
  161.         if (ret == E_EOF)
  162.             return 0;
  163.         /*
  164.         if (ret == E_NOMEM)
  165.             return -1;
  166.         */
  167.     }
  168. }
  169.  
  170. int
  171. run_tty_1(fp, filename)
  172.     FILE *fp;
  173.     char *filename;
  174. {
  175.     object *m, *d, *v, *w;
  176.     node *n;
  177.     perrdetail err;
  178.     char *ps1, *ps2;
  179.     v = sysget("ps1");
  180.     w = sysget("ps2");
  181.     if (v != NULL && is_stringobject(v)) {
  182.         INCREF(v);
  183.         ps1 = getstringvalue(v);
  184.     }
  185.     else {
  186.         v = NULL;
  187.         ps1 = "";
  188.     }
  189.     if (w != NULL && is_stringobject(w)) {
  190.         INCREF(w);
  191.         ps2 = getstringvalue(w);
  192.     }
  193.     else {
  194.         w = NULL;
  195.         ps2 = "";
  196.     }
  197.     BGN_SAVE
  198.     n = parsefile(fp, filename, &gram, single_input, ps1, ps2, &err);
  199.     END_SAVE
  200.     XDECREF(v);
  201.     XDECREF(w);
  202.     if (n == NULL) {
  203.         if (err.error == E_EOF) {
  204.             if (err.text)
  205.                 free(err.text);
  206.             return E_EOF;
  207.         }
  208.         err_input(&err);
  209.         print_error();
  210.         return err.error;
  211.     }
  212.     m = add_module("__main__");
  213.     if (m == NULL)
  214.         return -1;
  215.     d = getmoduledict(m);
  216.     v = run_node(n, filename, d, d);
  217.     if (v == NULL) {
  218.         print_error();
  219.         return -1;
  220.     }
  221.     DECREF(v);
  222.     flushline();
  223.     return 0;
  224. }
  225.  
  226. int
  227. run_script(fp, filename)
  228.     FILE *fp;
  229.     char *filename;
  230. {
  231.     object *m, *d, *v;
  232.     char *ext;
  233.  
  234.     m = add_module("__main__");
  235.     if (m == NULL)
  236.         return -1;
  237.     d = getmoduledict(m);
  238.     ext = filename + strlen(filename) - 4;
  239. #ifdef macintosh
  240.     /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
  241.     if ( strcmp(ext, ".pyc") == 0 || getfiletype(filename) == 'PYC ' ||
  242.                     getfiletype(filename) == 'APPL' ) {
  243. #else
  244.     if ( strcmp(ext, ".pyc") == 0 ) {
  245. #endif /* macintosh */
  246.         /* Try to run a pyc file. First, re-open in binary */
  247.         /* Don't close, done in main: fclose(fp); */
  248.         if( (fp = fopen(filename, "rb")) == NULL ) {
  249.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  250.             return -1;
  251.         }
  252.         v = run_pyc_file(fp, filename, d, d);
  253.     } else {
  254.         v = run_file(fp, filename, file_input, d, d);
  255.     }
  256.     if (v == NULL) {
  257.         print_error();
  258.         return -1;
  259.     }
  260.     DECREF(v);
  261.     flushline();
  262.     return 0;
  263. }
  264.  
  265. int
  266. run_command(command)
  267.     char *command;
  268. {
  269.     object *m, *d, *v;
  270.     m = add_module("__main__");
  271.     if (m == NULL)
  272.         return -1;
  273.     d = getmoduledict(m);
  274.     v = run_string(command, file_input, d, d);
  275.     if (v == NULL) {
  276.         print_error();
  277.         return -1;
  278.     }
  279.     DECREF(v);
  280.     flushline();
  281.     return 0;
  282. }
  283.  
  284. void
  285. print_error()
  286. {
  287.     object *exception, *v, *tb, *f;
  288.     err_fetch(&exception, &v, &tb);
  289.     flushline();
  290.     fflush(stdout);
  291.     if (exception == NULL)
  292.         fatal("print_error called but no exception");
  293.     if (exception == SystemExit) {
  294.         if (v == NULL || v == None)
  295.             goaway(0);
  296.         if (is_intobject(v))
  297.             goaway((int)getintvalue(v));
  298.         else {
  299.             /* OK to use real stderr here */
  300.             printobject(v, stderr, PRINT_RAW);
  301.             fprintf(stderr, "\n");
  302.             goaway(1);
  303.         }
  304.     }
  305.     sysset("last_type", exception);
  306.     sysset("last_value", v);
  307.     sysset("last_traceback", tb);
  308.     f = sysget("stderr");
  309.     if (f == NULL)
  310.         fprintf(stderr, "lost sys.stderr\n");
  311.     else {
  312.         tb_print(tb, f);
  313.         if (exception == SyntaxError) {
  314.             object *message;
  315.             char *filename, *text;
  316.             int lineno, offset;
  317.             if (!getargs(v, "(O(ziiz))", &message,
  318.                      &filename, &lineno, &offset, &text))
  319.                 err_clear();
  320.             else {
  321.                 char buf[10];
  322.                 writestring("  File \"", f);
  323.                 if (filename == NULL)
  324.                     writestring("<string>", f);
  325.                 else
  326.                     writestring(filename, f);
  327.                 writestring("\", line ", f);
  328.                 sprintf(buf, "%d", lineno);
  329.                 writestring(buf, f);
  330.                 writestring("\n", f);
  331.                 if (text != NULL) {
  332.                     char *nl;
  333.                     if (offset > 0 &&
  334.                         offset == strlen(text))
  335.                         offset--;
  336.                     for (;;) {
  337.                         nl = strchr(text, '\n');
  338.                         if (nl == NULL ||
  339.                             nl-text >= offset)
  340.                             break;
  341.                         offset -= (nl+1-text);
  342.                         text = nl+1;
  343.                     }
  344.                     while (*text == ' ' || *text == '\t') {
  345.                         text++;
  346.                         offset--;
  347.                     }
  348.                     writestring("    ", f);
  349.                     writestring(text, f);
  350.                     if (*text == '\0' ||
  351.                         text[strlen(text)-1] != '\n')
  352.                         writestring("\n", f);
  353.                     writestring("    ", f);
  354.                     offset--;
  355.                     while (offset > 0) {
  356.                         writestring(" ", f);
  357.                         offset--;
  358.                     }
  359.                     writestring("^\n", f);
  360.                 }
  361.                 INCREF(message);
  362.                 DECREF(v);
  363.                 v = message;
  364.             }
  365.         }
  366.         if (is_classobject(exception)) {
  367.             object* className = ((classobject*)exception)->cl_name;
  368.             if (className == NULL)
  369.                 writestring("<unknown>", f);
  370.             else {
  371.                 if (writeobject(className, f, PRINT_RAW) != 0)
  372.                     err_clear();
  373.             }
  374.         } else {
  375.             if (writeobject(exception, f, PRINT_RAW) != 0)
  376.                 err_clear();
  377.         }
  378.         if (v != NULL && v != None) {
  379.             writestring(": ", f);
  380.             if (writeobject(v, f, PRINT_RAW) != 0)
  381.                 err_clear();
  382.         }
  383.         writestring("\n", f);
  384.     }
  385.     XDECREF(exception);
  386.     XDECREF(v);
  387.     XDECREF(tb);
  388. }
  389.  
  390. object *
  391. run_string(str, start, globals, locals)
  392.     char *str;
  393.     int start;
  394.     object *globals, *locals;
  395. {
  396.     return run_err_node(parse_string(str, start),
  397.                 "<string>", globals, locals);
  398. }
  399.  
  400. object *
  401. run_file(fp, filename, start, globals, locals)
  402.     FILE *fp;
  403.     char *filename;
  404.     int start;
  405.     object *globals, *locals;
  406. {
  407.     return run_err_node(parse_file(fp, filename, start),
  408.                 filename, globals, locals);
  409. }
  410.  
  411. static object *
  412. run_err_node(n, filename, globals, locals)
  413.     node *n;
  414.     char *filename;
  415.     object *globals, *locals;
  416. {
  417.     if (n == NULL)
  418.         return  NULL;
  419.     return run_node(n, filename, globals, locals);
  420. }
  421.  
  422. static object *
  423. run_node(n, filename, globals, locals)
  424.     node *n;
  425.     char *filename;
  426.     object *globals, *locals;
  427. {
  428.     codeobject *co;
  429.     object *v;
  430.     co = compile(n, filename);
  431.     freetree(n);
  432.     if (co == NULL)
  433.         return NULL;
  434.     v = eval_code(co, globals, locals);
  435.     DECREF(co);
  436.     return v;
  437. }
  438.  
  439. static object *
  440. run_pyc_file(fp, filename, globals, locals)
  441.     FILE *fp;
  442.     char *filename;
  443.     object *globals, *locals;
  444. {
  445.     codeobject *co;
  446.     object *v;
  447.     long magic;
  448.     long get_pyc_magic();
  449.  
  450.     magic = rd_long(fp);
  451.     if (magic != get_pyc_magic()) {
  452.         err_setstr(RuntimeError,
  453.                "Bad magic number in .pyc file");
  454.         return NULL;
  455.     }
  456.     (void) rd_long(fp);
  457.     v = rd_object(fp);
  458.     fclose(fp);
  459.     if (v == NULL || !is_codeobject(v)) {
  460.         XDECREF(v);
  461.         err_setstr(RuntimeError,
  462.                "Bad code object in .pyc file");
  463.         return NULL;
  464.     }
  465.     co = (codeobject *)v;
  466.     v = eval_code(co, globals, locals);
  467.     DECREF(co);
  468.     return v;
  469. }
  470.  
  471. object *
  472. compile_string(str, filename, start)
  473.     char *str;
  474.     char *filename;
  475.     int start;
  476. {
  477.     node *n;
  478.     codeobject *co;
  479.     n = parse_string(str, start);
  480.     if (n == NULL)
  481.         return NULL;
  482.     co = compile(n, filename);
  483.     freetree(n);
  484.     return (object *)co;
  485. }
  486.  
  487. /* Simplified interface to parsefile -- return node or set exception */
  488.  
  489. node *
  490. parse_file(fp, filename, start)
  491.     FILE *fp;
  492.     char *filename;
  493.     int start;
  494. {
  495.     node *n;
  496.     perrdetail err;
  497.     BGN_SAVE
  498.     n = parsefile(fp, filename, &gram, start,
  499.                 (char *)0, (char *)0, &err);
  500.     END_SAVE
  501.     if (n == NULL)
  502.         err_input(&err);
  503.     return n;
  504. }
  505.  
  506. /* Simplified interface to parsestring -- return node or set exception */
  507.  
  508. node *
  509. parse_string(str, start)
  510.     char *str;
  511.     int start;
  512. {
  513.     node *n;
  514.     perrdetail err;
  515.     n = parsestring(str, &gram, start, &err);
  516.     if (n == NULL)
  517.         err_input(&err);
  518.     return n;
  519. }
  520.  
  521. /* Set the error appropriate to the given input error code (see errcode.h) */
  522.  
  523. static void
  524. err_input(err)
  525.     perrdetail *err;
  526. {
  527.     object *v, *w;
  528.     char *msg = NULL;
  529.     v = mkvalue("(ziiz)", err->filename,
  530.                 err->lineno, err->offset, err->text);
  531.     if (err->text != NULL) {
  532.         free(err->text);
  533.         err->text = NULL;
  534.     }
  535.     switch (err->error) {
  536.     case E_SYNTAX:
  537.         msg = "invalid syntax";
  538.         break;
  539.     case E_TOKEN:
  540.         msg = "invalid token";
  541.  
  542.         break;
  543.     case E_INTR:
  544.         err_set(KeyboardInterrupt);
  545.         return;
  546.     case E_NOMEM:
  547.         err_nomem();
  548.         return;
  549.     case E_EOF:
  550.         msg = "unexpected EOF while parsing";
  551.         break;
  552.     default:
  553.         fprintf(stderr, "error=%d\n", err->error);
  554.         msg = "unknown parsing error";
  555.         break;
  556.     }
  557.     w = mkvalue("(sO)", msg, v);
  558.     XDECREF(v);
  559.     err_setval(SyntaxError, w);
  560.     XDECREF(w);
  561. }
  562.  
  563. /* Print fatal error message and abort */
  564.  
  565. void
  566. fatal(msg)
  567.     char *msg;
  568. {
  569.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  570. #ifdef macintosh
  571.     for (;;);
  572. #endif
  573. #ifdef NT
  574.     OutputDebugString("Fatal Python error:");
  575.     OutputDebugString(msg);
  576.     OutputDebugString("\n");
  577. #endif
  578.     abort();
  579. }
  580.  
  581. /* Clean up and exit */
  582.  
  583. #ifdef WITH_THREAD
  584. #include "thread.h"
  585. int threads_started = 0; /* Set by threadmodule.c and maybe others */
  586. #endif
  587.  
  588. #define NEXITFUNCS 32
  589. static void (*exitfuncs[NEXITFUNCS])();
  590. static int nexitfuncs = 0;
  591.  
  592. int Py_AtExit(func)
  593.     void (*func) PROTO((void));
  594. {
  595.     if (nexitfuncs >= NEXITFUNCS)
  596.         return -1;
  597.     exitfuncs[nexitfuncs++] = func;
  598.     return 0;
  599. }
  600.  
  601. void
  602. cleanup()
  603. {
  604.     object *exitfunc = sysget("exitfunc");
  605.  
  606.     if (exitfunc) {
  607.         object *res;
  608.         INCREF(exitfunc);
  609.         sysset("exitfunc", (object *)NULL);
  610.         res = call_object(exitfunc, (object *)NULL);
  611.         if (res == NULL) {
  612.             fprintf(stderr, "Error in sys.exitfunc:\n");
  613.             print_error();
  614.         }
  615.         DECREF(exitfunc);
  616.     }
  617.  
  618.     flushline();
  619.  
  620.     while (nexitfuncs > 0)
  621.         (*exitfuncs[--nexitfuncs])();
  622. }
  623.  
  624. #ifdef COUNT_ALLOCS
  625. extern void dump_counts PROTO((void));
  626. #endif
  627.  
  628. void
  629. goaway(sts)
  630.     int sts;
  631. {
  632.     cleanup();
  633.  
  634. #ifdef COUNT_ALLOCS
  635.     dump_counts();
  636. #endif
  637.  
  638. #ifdef WITH_THREAD
  639.  
  640.     /* Other threads may still be active, so skip most of the
  641.        cleanup actions usually done (these are mostly for
  642.        debugging anyway). */
  643.     
  644.     (void) save_thread();
  645. #ifndef NO_EXIT_PROG
  646.     if (threads_started)
  647.         _exit_prog(sts);
  648.     else
  649.         exit_prog(sts);
  650. #else /* !NO_EXIT_PROG */
  651.     if (threads_started)
  652.         _exit(sts);
  653.     else
  654.         exit(sts);
  655. #endif /* !NO_EXIT_PROG */
  656.     
  657. #else /* WITH_THREAD */
  658.     
  659.     doneimport();
  660.     
  661.     err_clear();
  662.  
  663. #ifdef REF_DEBUG
  664.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  665. #endif
  666.  
  667. #ifdef TRACE_REFS
  668.     if (askyesno("Print left references?")) {
  669.         printrefs(stderr);
  670.     }
  671. #endif /* TRACE_REFS */
  672.  
  673.     /* XXXX Jack thinks it would be nicer to pause if any output has
  674.     ** been generated since the last interaction with the user...
  675.     */
  676. #ifdef THINK_C
  677.     if (sts == 0)
  678.         console_options.pause_atexit = 0;
  679. #endif
  680. #ifdef __MWERKS__
  681.     if (sts == 0)
  682.         SIOUXSettings.autocloseonquit = 1;
  683.     else
  684.         printf("\n[Terminated]\n");
  685. #endif
  686.     exit(sts);
  687. #endif /* WITH_THREAD */
  688.     /*NOTREACHED*/
  689. }
  690.  
  691. #ifdef HAVE_SIGNAL_H
  692. static RETSIGTYPE
  693. sighandler(sig)
  694.     int sig;
  695. {
  696.     signal(sig, SIG_DFL); /* Don't catch recursive signals */
  697.     cleanup(); /* Do essential clean-up */
  698. #ifdef HAVE_GETPID
  699.     kill(getpid(), sig); /* Pretend the signal killed us */
  700. #else
  701.     exit(1);
  702. #endif
  703.     /*NOTREACHED*/
  704. }
  705. #endif
  706.  
  707. static void
  708. initsigs()
  709. {
  710.     RETSIGTYPE (*t)();
  711. #ifdef HAVE_SIGNAL_H
  712. #ifdef SIGPIPE
  713.     signal(SIGPIPE, SIG_IGN);
  714. #endif
  715. #ifdef SIGHUP
  716.     t = signal(SIGHUP, SIG_IGN);
  717.     if (t == SIG_DFL)
  718.         signal(SIGHUP, sighandler);
  719.     else
  720.         signal(SIGHUP, t);
  721. #endif              
  722. #ifdef SIGTERM
  723.     t = signal(SIGTERM, SIG_IGN);
  724.     if (t == SIG_DFL)
  725.         signal(SIGTERM, sighandler);
  726.     else
  727.         signal(SIGTERM, t);
  728. #endif
  729. #endif /* HAVE_SIGNAL_H */
  730.     initintr(); /* May imply initsignal() */
  731. }
  732.  
  733. #ifdef TRACE_REFS
  734. /* Ask a yes/no question */
  735.  
  736. int
  737. askyesno(prompt)
  738.     char *prompt;
  739. {
  740.     char buf[256];
  741.     
  742.     printf("%s [ny] ", prompt);
  743.     if (fgets(buf, sizeof buf, stdin) == NULL)
  744.         return 0;
  745.     return buf[0] == 'y' || buf[0] == 'Y';
  746. }
  747. #endif
  748.  
  749. #ifdef MPW
  750.  
  751. /* Check for file descriptor connected to interactive device.
  752.    Pretend that stdin is always interactive, other files never. */
  753.  
  754. int
  755. isatty(fd)
  756.     int fd;
  757. {
  758.     return fd == fileno(stdin);
  759. }
  760.  
  761. #endif
  762.